/**
 * Notes: 兼职模块业务逻辑
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2024-03-23 04:00:00 
 */

const BaseProjectService = require('./base_project_service.js');
const dataUtil = require('../../../framework/utils/data_util.js');
const timeUtil = require('../../../framework/utils/time_util.js');
const util = require('../../../framework/utils/util.js');
const cloudUtil = require('../../../framework/cloud/cloud_util.js');
const cloudBase = require('../../../framework/cloud/cloud_base.js');
const LeaveModel = require('../model/leave_model.js');
const UserModel = require('../model/user_model.js');
const fs = require('fs');

class LeaveService extends BaseProjectService {

	/** 点赞 */
  async likeLeave(userId, id) {
    try {
        // 获取留言详情
        let like = await this.getLeaveDetail(id);
        if (!like) {
            return {
                code: -1,
                message: '点赞信息不存在',
                data: null
            };
        }
        
        // 获取当前点赞列表
        let arr = like['LEAVE_LIKE_LIST'];

        // 定义一个标志位，用于表示是否已经点赞
        let flag = false;

        // 检查用户是否已经在点赞列表中
        if (arr.includes(userId)) {
            // 如果用户已经点赞了，则取消点赞
            arr = arr.filter(item => item != userId);
            flag = false; // 表示取消点赞
        } else {
            // 如果用户未点赞，则执行点赞操作
            arr.push(userId);
            flag = true; // 表示点赞
        }
        
        // 更新留言详情中的点赞列表和点赞数量
        await LeaveModel.edit(id, {
            ["LEAVE_LIKE_LIST"]: arr,
            ["LEAVE_LIKE_CNT"]: arr.length
        });

        return {
          isLike:flag
        };
    } catch (err) {
        console.error('[点赞操作失败]', err);
        return {
            code: -1,
            message: '点赞操作失败：' + err.message,
            data: null
        };
    }
}

	/** 浏览 */
	async viewLeave(userId, id) {
		let fields = '*';

		let where = {
			_id: id,
			//LEAVE_STATUS: 1
		}

		if (userId && util.isDefined(where.LEAVE_STATUS)) delete where.LEAVE_STATUS;

		let leave = await LeaveModel.getOne(where, fields);
		if (!leave) return null;

		LeaveModel.inc(id, 'LEAVE_VIEW_CNT', 1);

		return leave;
	}

	/** 获取 */
	async getLeaveDetail(id) {
		return await LeaveModel.getOne(id);
	}

/** 修改状态 */
async statusLeave(userId, id, status) {
  try {
      // 获取失物招领详情
      let leave = await this.getLeaveDetail(id);
      if (!leave) {
          return {
              code: -1,
              message: '失物招领不存在',
              data: null
          };
      }

      // 检查用户权限
      if (leave.LEAVE_USER_ID !== userId) {
          return {
              code: -1,
              message: '您无权修改该失物招领状态',
              data: null
          };
      }

      // 更新状态
      await leaveModel.edit(id, { LEAVE_STATUS: status });

      return {
          code: 0,
          message: '修改闲置状态成功',
          data: null
      };
  } catch (err) {
      console.error('[修改闲置状态失败]', err);
      return {
          code: -1,
          message: '修改闲置状态失败：' + err.message,
          data: null
      };
  }
}

	/** 删除 */
  async delLeave(userId, id) {
    try {
        await LeaveModel.del(userId,id);
        return {
            code: 0,
            message: '删除闲置物品成功',
            data: null
        };
    } catch (err) {
        console.error('[删除闲置物品失败]', err);
        return {
            code: -1,
            message: '删除留言失败：' + err.message,
            data: null
        };
    }
}

	/** 插入 */
	async insertLeave(userId, {
		cateId,
		cateName,
		order,
		forms
	}) {
    try {
      let data = {
        LEAVE_USER_ID : userId,
        LEAVE_CATE_ID : cateId,
        LEAVE_CATE_NAME : cateName,
        LEAVE_ORDER : order ,
        LEAVE_OBJ : dataUtil.dbForms2Obj(forms),
        LEAVE_FORMS : forms
      }
      await LeaveModel.insert(data);
        // 返回插入成功的结果
      return {
        code: 0,
        message: '插入闲置物品成功',
        data
      };
    }catch (err) {
        // 如果发生错误，可以捕获错误并进行处理
        console.error('[插入闲置物品失败]', err);
        // 返回错误信息
        return {
            code: -1,
            message: '插入闲置物品失败：' + err.message,
            data: null
        };
    }
	}

	/** 修改 */
  async editLeave(userId, {
    id,
    cateId,
    cateName,
    order,
    forms
}) {
    try {
        let data = {
            LEAVE_CATE_ID: cateId,
            LEAVE_CATE_NAME: cateName,
            LEAVE_ORDER: order,
            LEAVE_OBJ: dataUtil.dbForms2Obj(forms),
            LEAVE_FORMS: forms
        };

        let result = await LeaveModel.edit(id,data);
        return {
            code: 0,
            message: '修改留言成功',
            data: result
        };
    } catch (err) {
        console.error('[修改留言失败]', err);
        return {
            code: -1,
            message: '修改留言失败：' + err.message,
            data: null
        };
    }
}


  /** 更新forms信息 */
  async updateLeaveForms({
    id,
    images
}) {
    try {
        const cloud = cloudBase.getCloud();
        const fileIDs = await Promise.all(images.map(async image => {
            const res = await cloud.uploadFile({
                cloudPath: 'leave_images/' + dataUtil.getUniqueFileName(image.name),
                fileContent: image.data,
            });
            return res.fileID;
        }));

        const result = await LeaveModel.edit(id, { LEAVE_IMAGES: fileIDs });
        return {
            code: 0,
            message: '更新留言图片成功',
            data: result
        };
    } catch (err) {
        console.error('[更新留言图片失败]', err);
        return {
            code: -1,
            message: '更新留言图片失败：' + err.message,
            data: null
        };
    }
}

	/** 列表与搜索 */
	async getLeaveList(userId, {
		search, // 搜索条件
		sortType, // 搜索菜单
		sortVal, // 搜索菜单
		orderBy, // 排序
		whereEx, //附加查询条件
		page,
		size,
		isTotal = true,
		oldTotal }) {
		orderBy = orderBy || {
			'LEAVE_ORDER': 'asc',
			'LEAVE_ADD_TIME': 'desc'
		};
		let fields = 'LEAVE_ORDER,LEAVE_CATE_ID,LEAVE_CATE_NAME,LEAVE_STATUS,LEAVE_COMMENT_CNT,LEAVE_VIEW_CNT,LEAVE_FAV_CNT,LEAVE_FAV_LIST,LEAVE_LIKE_CNT,LEAVE_LIKE_LIST,LEAVE_ADD_TIME,LEAVE_USER_ID,LEAVE_OBJ,user.USER_NAME,user.USER_PIC';

		let where = {};
		where.and = {
			//LEAVE_STATUS: 1,
			_pid: this.getProjectId() //复杂的查询在此处标注PID
		};


		if (util.isDefined(search) && search) {
			if (search == '我的发布') {
				where.and.LEAVE_USER_ID = userId;
			}
			else if (search == '我的点赞') {
				where.and.LEAVE_LIKE_LIST = userId;
			}
			else if (search == '我的收藏') {
				where.and.LEAVE_FAV_LIST = userId;
			}
			else {
				where.or = [
					{ 'LEAVE_OBJ.title': ['like', search] },
					{ 'LEAVE_OBJ.poster': ['like', search] },
					{ 'LEAVE_OBJ.tel': ['like', search] },
					{ 'LEAVE_OBJ.wx': ['like', search] }, 
					{ 'LEAVE_OBJ.desc': ['like', search] },
				];
			}

		} else if (sortType && util.isDefined(sortVal)) {
			// 搜索菜单
			switch (sortType) {
				case 'cateId': {
					where.and.LEAVE_CATE_ID = String(sortVal);
					break;
				}
				case 'status': {
					where.and.LEAVE_STATUS = Number(sortVal);
					break;
				}
				case 'sort': {
					orderBy = this.fmtOrderBySort(sortVal, 'LEAVE_ADD_TIME');
					break;
				}
				case 'fav': {
					orderBy = {
						'LEAVE_FAV_CNT': 'desc',
						'LEAVE_ADD_TIME': 'desc'
					}
					break;
				}
				case 'comment': {
					orderBy = {
						'LEAVE_COMMENT_CNT': 'desc',
						'LEAVE_ADD_TIME': 'desc'
					}
					break;
				}
				case 'like': {
					orderBy = {
						'LEAVE_LIKE_CNT': 'desc',
						'LEAVE_ADD_TIME': 'desc'
					}
					break;
				}
				case 'today': {
					where.and.LEAVE_DAY = timeUtil.time('Y-M-D');
					break;
				}
				case 'yesterday': {
					where.and.LEAVE_DAY = timeUtil.time('Y-M-D', -86400);
					break;
				}
			}
		}

		let joinParams = {
			from: UserModel.CL,
			localField: 'LEAVE_USER_ID',
			foreignField: 'USER_MINI_OPENID',
			as: 'user',
		};

		return await LeaveModel.getListJoin(joinParams, where, fields, orderBy, page, size, isTotal, oldTotal);

	}

}

module.exports = LeaveService;